import Toast from '../miniprogram_npm/@vant/weapp/toast/toast';
import { getLogin } from "../server/login"
import { getUser } from "../server/user"
const login = (data, type = "login") => {
  getLogin(data).then(res => {
    // console.log(res);
    wx.setStorageSync('access_token', res.access_token)
    getUser().then(res => {
      // console.log(res);
      wx.setStorageSync('userInfo', res)
            // let path = "/" + getCurrentPages().pop().route
      Toast({
        message: type == "login" ? '登录成功' : "注册成功",
        type: 'success',
        onClose: () => {
          if (type == "login" && !res.openid) {
            wx.redirectTo({
              url: '/pages/bind/bind',
            })
          } else {
            back()
          }
        }
      });

    })
  }).catch(err => {
    console.log(err);
  })
}

const back = () => {
  // let {route,} = getCurrentPages().pop()
  let path = wx.getStorageSync('path')
  // console.log(path);
  if (!path) {
    path = "/pages/index/index"
  }
  wx.reLaunch({
    url: path
  })
}

const checkLogin = () => {
  if (!wx.getStorageSync('access_token')) {
    let path = "/" + getCurrentPages().pop().route
    if(getCurrentPages().pop().options){
      let options1 = Object.keys(getCurrentPages().pop().options).reduce((pre,curr)=>{
        return pre + curr + "=" + getCurrentPages().pop().options[curr] + "&"
      },"?").slice(0,-1)
      path += options1
    }
    // console.log(path);
    wx.setStorageSync('path', path)
    wx.redirectTo({
      url: '/pages/login/login',
    })
  }
}


const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    getUser().then(res => {
      // console.log(res);
      wx.setStorageSync('userInfo', res)
      resolve()
    })
  })

}

export {
  login,
  back,
  checkLogin,
  getUserInfo
}